<template>
  <div>
    <el-tabs v-model="formTabActive" type="card">
      <el-tab-pane name="formInfo" label="基本信息"></el-tab-pane>
      <el-tab-pane name="formQualify" label="实名资质"></el-tab-pane>
    </el-tabs>
    <el-form ref="userFormInfo" v-show="formTabActive === 'formInfo'" :model="userFormInfo" :rules="userFormInfoRules"
      label-width="100px" v-loading="!userDataReady">
      <el-row class="line-text-title" type="flex" align="middle">
        <span class="title-medium text-important">基本信息</span>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="用户头像">
            <el-upload accept="image/jpeg,image/gif,image/png" ref="addItemDataUpload" :action="imageUploadUrl"
              :on-success="headUrlSuccess" :show-file-list="false" :drag="true">
              <img v-if="userFormInfo.headUrl" :src="userFormInfo.headUrl" class="avatar-uploader-img" alt="" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              <div slot="tip" class="el-upload__tip el-upload__tip_fix">
                只能上传jpg/png/bmp文件
              </div>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-row class="message-gutter">
            <el-col :span="12">
              <el-form-item label="姓名" prop="name">
                <el-input v-model="userFormInfo.name" placeholder="请输入用户姓名" class="input-form" size="mini" maxlength="20">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="手机" prop="phone">
                <el-input v-model.number="userFormInfo.phone" placeholder="请输入手机号码" class="input-form" size="mini"
                  maxlength="11">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row class="message-gutter">
            <el-col :span="12">
              <el-form-item label="所属机构" prop="institutionId">

                <el-select v-model="userFormInfo.institutionId" :disabled="!isPlatformManage || !isAddNew"
                  placeholder="请选择所属机构" class="picker-form" size="mini">
                  <el-option v-for="t in institutionList" :key="t.id" :label="t.name" :value="t.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="身份证" prop="idCard">
                <el-input v-model="userFormInfo.idCard" placeholder="请输入身份证号" class="input-form" size="mini">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row class="message-gutter">
            <el-col :span="12">
              <el-form-item label="登录名称" prop="account">
                <!-- :disabled="!isAddNew" -->
                <el-input v-model="userFormInfo.account" placeholder="请输入登录名称" class="input-form" size="mini">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所在地">
                <el-cascader v-model="userFormInfo.areaSelected" placeholder="请选择所在地" :options="areaList"
                  :props="areaProps" class="picker-form" size="mini" clearable>
                </el-cascader>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="性别">
            <el-radio-group v-model="userFormInfo.gender" size="mini" class="radio-group">
              <el-radio v-for="t in genderList" :label="t.id" :key="t.id" size="mini">
                {{ t.name }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="学历">
            <el-input v-model="userFormInfo.education" placeholder="请输入学历" class="input-form" size="mini"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="专业">
            <el-input v-model="userFormInfo.major" placeholder="请输入专业" class="input-form" size="mini"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="推荐首页">
            <el-radio-group v-model="userFormInfo.isRecommend" size="mini" class="radio-group">
              <el-radio v-for="t in RecommendList" :label="t.id" :key="t.id" size="mini">
                {{ t.name }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-show="userFormInfo.isRecommend == 0">
          <el-form-item label="推荐序号">
            <el-input v-model.number="userFormInfo.recommendIndex" placeholder="请输入推荐序号" class="input-form"
              size="mini"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="会诊诊断医生">
            <el-radio-group v-model="userFormInfo.isParticipationConsultation" size="mini" class="radio-group">
              <el-radio v-for="t in isParticipationConsultationList" :label="t.id" :key="t.id" size="mini">
                {{ t.name }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <span class="title-medium text-important">角色</span>
      <el-row class="row-class">
        <el-col :span="8">
          <el-form-item label="角色" prop="roles">
            <el-select v-model="userFormInfo.roleSelected" placeholder="请选择角色" class="picker-form"
              style="max-width: unset; width: 400px" size="mini" multiple>
              <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <span class="title-medium text-important">扩展信息</span>
      <el-row class="row-class">
        <el-col :span="8">
          <el-form-item label="签名照片">
            <el-upload accept="image/jpeg,image/gif,image/png" ref="addItemDataUpload1" :action="imageUploadUrl"
              :on-success="signUrlSuccess" :show-file-list="false" :drag="true">
              <img v-if="userFormInfo.signUrl" :src="userFormInfo.signUrl" class="avatar-uploader-img" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              <div slot="tip" class="el-upload__tip el-upload__tip_fix">
                只能上传jpg/png/bmp文件
              </div>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-row class="message-gutter">
            <el-col :span="12">
              <el-form-item label="电子邮箱" prop="email">
                <el-input v-model="userFormInfo.email" placeholder="请输入电子邮箱" class="input-form" size="mini">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="职级">
                <el-select v-model="userFormInfo.position" placeholder="请选择职级" class="picker-form" size="mini">
                  <el-option v-for="t in positionList" :key="t.id" :label="t.name" :value="t.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row class="message-gutter">
            <el-col :span="12">
              <el-form-item label="社会任职">
                <el-input v-model="userFormInfo.socialPosition" placeholder="请输入社会任职" class="input-form" size="mini">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="职称">
                <el-select v-model="userFormInfo.medicalTitle" placeholder="请选择职称" class="picker-form" size="mini">
                  <el-option v-for="t in medicalTitleList" :key="t.id" :label="t.name" :value="t.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row class="message-gutter">
            <!-- 特长用了remark字段 -->
            <!-- <el-col :span="12">
                            <el-form-item label="特长">
                                <el-input
                                    v-model="userFormInfo.speciality"
                                    placeholder="请输入特长"
                                    class="input-form"
                                    size="mini"
                                >
                                </el-input>
                            </el-form-item>
                        </el-col> -->
            <el-col :span="12">
              <el-form-item label="工龄">
                <el-input v-model.number="userFormInfo.workYear" placeholder="请输入工龄" class="input-form" size="mini">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
      <el-row class="row-class">
        <el-col>
          <el-form-item label="个人简介">
            <el-input v-model="userFormInfo.introduce" placeholder="请输入个人简介" type="textarea" :rows="3"
              style="width: 100%">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row class="row-class">
        <el-col>
          <el-form-item label="特长">
            <el-input v-model="userFormInfo.remark" placeholder="请输入特长" type="textarea" :rows="3" style="width: 100%">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-form ref="userFormQualify" v-show="formTabActive === 'formQualify'" :model="userFormQualify" label-width="160px"
      v-loading="!userDataReady">
      <span class="title-medium text-important">实名认证</span>
      <el-row class="row-class">
        <el-form-item label="手持身份证照片">
          <el-upload accept="image/jpeg,image/gif,image/png" ref="idCardUrlUpload" :action="imageUploadUrl"
            :file-list="idCardUrlList" list-type="picture-card" :drag="true">
            <el-button size="mini" type="primary" style="margin-top: 57px"> 点击上传 </el-button>
            <div slot="tip" class="el-upload__tip el-upload__tip_fix">只能上传jpg/png/bmp文件</div>
          </el-upload>
        </el-form-item>
      </el-row>
      <span class="title-medium text-important">资质认证</span>
      <el-row class="row-class">
        <el-col :span="24">
          <el-form-item label="学历证书">
            <el-upload accept="image/jpeg,image/gif,image/png" ref="diplomaUrlUpload" :action="imageUploadUrl"
              :file-list="diplomaUrlList" list-type="picture-card" :drag="true">
              <el-button size="mini" type="primary" style="margin-top: 57px"> 点击上传 </el-button>
              <div slot="tip" class="el-upload__tip el-upload__tip_fix">
                只能上传jpg/png/bmp文件
              </div>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <span class="title-medium text-important">资质认证</span>
      <el-row class="row-class">
        <el-col :span="12">
          <el-form-item label="医生执业证书编号">
            <el-input v-model="userFormQualify.practiceCode" placeholder="请输入医生执业证书编号" class="input-form"
              size="mini"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="医生执业证书编号正面">
            <el-upload accept="image/jpeg,image/gif,image/png" ref="practiceUrlFUpload" :action="imageUploadUrl"
              :file-list="practiceUrlFList" list-type="picture-card" :drag="true">
              <el-button size="mini" type="primary" style="margin-top: 57px"> 点击上传 </el-button>
              <div slot="tip" class="el-upload__tip el-upload__tip_fix">
                只能上传jpg/png/bmp文件
              </div>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="医生执业证书编号反面">
            <el-upload accept="image/jpeg,image/gif,image/png" ref="practiceUrlRUpload" :action="imageUploadUrl"
              :file-list="practiceUrlRList" list-type="picture-card" :drag="true">
              <el-button size="mini" type="primary" style="margin-top: 57px"> 点击上传 </el-button>
              <div slot="tip" class="el-upload__tip el-upload__tip_fix">
                只能上传jpg/png/bmp文件
              </div>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="医师资格证书编号">
            <el-input v-model="userFormQualify.qualificationCode" placeholder="医师资格证书编号" class="input-form"
              size="mini"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="医师资格证书编号正面">
            <el-upload accept="image/jpeg,image/gif,image/png" ref="qualificationUrlFUpload" :action="imageUploadUrl"
              :file-list="qualificationUrlFList" list-type="picture-card" :drag="true">
              <el-button size="mini" type="primary" style="margin-top: 57px"> 点击上传 </el-button>
              <div slot="tip" class="el-upload__tip el-upload__tip_fix">
                只能上传jpg/png/bmp文件
              </div>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="医师资格证书编号反面">
            <el-upload accept="image/jpeg,image/gif,image/png" ref="qualificationUrlRUpload" :action="imageUploadUrl"
              :file-list="qualificationUrlRList" list-type="picture-card" :drag="true">
              <el-button size="mini" type="primary" style="margin-top: 57px"> 点击上传 </el-button>
              <div slot="tip" class="el-upload__tip el-upload__tip_fix">
                只能上传jpg/png/bmp文件
              </div>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="医生工牌照片">
            <el-upload accept="image/jpeg,image/gif,image/png" ref="jobUrlUpload" :action="imageUploadUrl"
              :file-list="jobUrlList" list-type="picture-card" :drag="true">
              <el-button size="mini" type="primary" style="margin-top: 57px"> 点击上传 </el-button>
              <div slot="tip" class="el-upload__tip el-upload__tip_fix">
                只能上传jpg/png/bmp文件
              </div>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-row type="flex" justify="center" style="margin-top: 20px">
      <el-button @click="submitForm" type="primary" size="mini">提交</el-button>
      <el-button @click="goBack" size="mini">返回</el-button>
    </el-row>
    <el-dialog title="提示" :visible.sync="isAddSuccess" :modal-append-to-body="false" :show-close="false" append-to-body
      center width="60%">
      <div class="success-page">
        <div class="success-icon">
          <i class="el-icon-success"></i>
        </div>
        <div class="success-h1">
          <span>新增用户成功</span>
        </div>
      </div>
      <span slot="footer" class="dialog-footer" style="text-align: right">
        <el-button @click="goBack" size="mini">返回用户列表</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'

export default {
  name: 'UserEdit',
  data() {
    const checkName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入姓名'))
      }
      // if (false) {
      //   return callback(new Error('长度在 1 到 10 个字符'));
      // }
      return callback()
    }
    const checkAccount = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入登录名称'))
      }
      return callback()
    }

    const checkInstitution = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请选择所属机构'))
      }
      return callback()
    }
    const checkPhone = (rule, value, callback) => {
      const reg = /^1[3|4|5|7|8][0-9]\d{8}$/
      if (!value) {
        return callback(new Error('请输入手机号'))
      }
      if (!reg.test(value)) {
        return callback(new Error('手机号不正确'))
      }
      // if (this.checkPhoneOnly(value)) {
      //   return callback(new Error('手机号已使用'));
      // }
      return callback()
    }
    const checkRole = (rule, value, callback) => {
      if (this.userFormInfo.roleSelected.length === 0) {
        return callback(new Error('请选择角色'))
      }
      return callback()
    }
    const checkIdCard = (rule, value, callback) => {
      if (!value) {
        return callback()
      }
      const reg =
        /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
      if (reg.test(value)) {
        return callback()
      }
      return callback(new Error('身份证格式不正确'))
    }
    console.log(process.env)
    return {
      uArgs: this.$store.getters.getUArgs,
      imageServiceURL: process.env.VUE_APP_ImageServiceURL,
      imageUploadUrl: `${process.env.VUE_APP_ImageServiceURL}/upload`,

      dictionaryMap: [
        {
          code: 'SexKind',
          array: 'genderList'
        },
        {
          code: 'PostKind',
          array: 'positionList'
        },
        {
          code: 'TitleForClinic',
          array: 'medicalTitleList'
        }
      ],

      // 从接口返回的用户数据
      userData: {},

      formTabActive: 'formInfo',
      userFormInfo: {
        // 用户头像
        headUrl: '',
        name: '',
        account: '',
        phone: '',
        institutionId: '',
        idCard: '',
        // jobNumber: '', // 会诊无工号
        areaSelected: [], // 接口没有同名字段
        gender: '',
        isRecommend: '', //推荐到首页 0-是 1-否
        isParticipationConsultation: '', //是否参与会诊 0-否 1-是
        recommendIndex: '',
        education: '',
        major: '',
        roleSelected: [], // 接口没有同名字段
        signUrl: '',
        email: '',
        position: '',
        socialPosition: '',
        medicalTitle: '',
        speciality: '',
        workYear: '',
        introduce: '',
        remark: ''
      },
      // 表单数据
      userFormQualify: {
        // 医生执业证书编号
        practiceCode: '',
        // 医师资格证书编号
        qualificationCode: '',
        // 手持身份证照片文件列表 url
        idCardUrl: '',
        // 学历证书文件列表 url
        diplomaUrl: '',
        // 医师执业正面照文件列表 url
        practiceUrlF: '',
        // 医师执业反面照文件列表 url
        practiceUrlR: '',
        // 医师资格正面照文件列表 url
        qualificationUrlF: '',
        // 医师资格反面照文件列表 url
        qualificationUrlR: '',
        // 医生工牌照片文件列表 url
        jobUrl: ''
      },

      userFormInfoRules: {
        name: [{ required: true, validator: checkName, trigger: 'blur' }],
        account: [{ required: true, validator: checkAccount, trigger: 'blur' }],
        phone: [{ required: true, validator: checkPhone, trigger: 'blur' }],
        roles: [{ required: true, validator: checkRole, trigger: 'blur' }],
        institutionId: [{ required: true, validator: checkInstitution, trigger: 'blur' }],
        email: [
          { required: false, trigger: 'blur' },
          { type: 'email', trigger: ['blur', 'change'], message: '邮箱格式不正确' }
        ],
        idCard: [{ required: false, trigger: 'blur', validator: checkIdCard }],
        workYear: [{ required: false, trigger: 'blur', type: 'number', message: '工龄应该为数字' }]
      },

      // 手持身份证照片文件列表
      idCardUrlList: [],
      // 学历证书文件列表
      diplomaUrlList: [],
      // 医师执业正面照文件列表
      practiceUrlFList: [],
      // 医师执业反面照文件列表
      practiceUrlRList: [],
      // 医师资格正面照文件列表
      qualificationUrlFList: [],
      // 医师资格反面照文件列表
      qualificationUrlRList: [],
      // 医生工牌照片文件列表
      jobUrlList: [],

      imageUrlMap: [
        {
          stringKey: 'idCardUrl',
          arrayKey: 'idCardUrlList',
          ref: 'idCardUrlUpload'
        },
        {
          stringKey: 'diplomaUrl',
          arrayKey: 'diplomaUrlList',
          ref: 'diplomaUrlUpload'
        },
        {
          stringKey: 'practiceUrlF',
          arrayKey: 'practiceUrlFList',
          ref: 'practiceUrlFUpload'
        },
        {
          stringKey: 'practiceUrlR',
          arrayKey: 'practiceUrlRList',
          ref: 'practiceUrlRUpload'
        },
        {
          stringKey: 'qualificationUrlF',
          arrayKey: 'qualificationUrlFList',
          ref: 'qualificationUrlFUpload'
        },
        {
          stringKey: 'qualificationUrlR',
          arrayKey: 'qualificationUrlRList',
          ref: 'qualificationUrlRUpload'
        },
        {
          stringKey: 'jobUrl',
          arrayKey: 'jobUrlList',
          ref: 'jobUrlUpload'
        }
      ],

      institutionList: [],
      areaList: [],
      areaProps: {
        value: 'id',
        label: 'name',
        children: 'childrenList'
      },
      genderList: [],
      RecommendList: [
        { id: 0, name: '是' },
        { id: 1, name: '否' }
      ],
      isParticipationConsultationList: [
        { id: 1, name: '是' },
        { id: 0, name: '否' }
      ],
      roleList: [],
      positionList: [],
      medicalTitleList: [],

      userDataReady: false,
      isAddSuccess: false
    }
  },

  computed: {
    // 当前是否为平台管理 - 编辑
    isPlatformManage() {
      return !!this.uArgs.isPlatformManage
    },
    // 是否为新增用户
    isAddNew() {
      return !!this.uArgs.isAddNew
    },
    // 当前编辑的用户Id
    uUserId() {
      return this.uArgs.userId
    },
    // 目标机构Id
    uInstitutionId() {
      return this.uArgs.institutionId
    }
  },
  async mounted() {
    // 获取字典
    this.dictionaryMap.forEach(map => {
      this.$axios({
        method: 'GET',
        url: '/dicts/list',
        params: {
          code: map.code,
          page: 0,
          size: 99
        }
      }).then(res => {
        if (res && res.data.code === 200) {
          this[map.array] = _.clone(res.data.data)
        }
      })
    })
    // 获取行政区域数据
    this.getAreaList()
    // 获取角色数据
    this.getRoleList()
    // 获取机构列表
    this.getInstitutionList()
    if (this.isAddNew) {
      delete this.userFormInfo.id

      if (this.isPlatformManage) {
        // 获取机构列表
        //this.getInstitutionList()
      } else {
        // this.institutionList.push({
        //   id: this.$store.state.institution.id,
        //   name: this.$store.state.institution.name
        // })
        this.userFormInfo.institutionId = this.uInstitutionId
      }
      this.userDataReady = true
    } else {
      this.userFormInfo.id = this.uUserId
      this.getUser()
    }
  },

  methods: {
    // 获取行政区域数据
    getAreaList() {
      this.$axios({
        method: 'GET',
        url: '/provinces',
        params: {}
      }).then(res => {
        if (res && res.data.code === 200) {
          this.areaList = _.clone(res.data.data)
        }
      })
    },
    // 获取角色数据
    // getRoleList() {
    //   this.$axios({
    //     method: 'GET',
    //     url: '/roles',
    //     params: {
    //       size: 99
    //     }
    //   }).then(res => {
    //     if (res && res.data.code === 200) {
    //       res.data.data.forEach(t => {
    //         this.roleList.push({
    //           id: t.id,
    //           name: t.name
    //         })
    //       })
    //     }
    //   })
    // },

    getRoleList() {
      this.$axios({
        method: 'GET',
        url: '/roles/permissionRole'
      }).then(res => {
        if (res && res.data.code === 200) {
          res.data.data.forEach(t => {
            this.roleList.push({
              id: t.id,
              name: t.name
            })
          })
        }
      })
    },
    // 获取机构列表
    getInstitutionList() {
      this.$axios({
        method: 'POST',
        url: '/institutions/search',
        data: {
          page: 0,
          size: 99
        }
      }).then(res => {
        if (res && res.data.code === 200) {
          res.data.data.forEach(t => {
            this.institutionList.push({
              id: t.id,
              name: t.name
            })
          })
        }
      })
    },
    // 获取用户数据
    async getUser() {
      this.userDataReady = false
      const res = await this.$axios({
        method: 'GET',
        url: `/users/${this.uUserId}`
      })

      if (res && res.data.code === 200) {
        this.userData = _.clone(res.data.data.userInfo)
        const user = res.data.data.userInfo

        // 机构数据
        this.institutionList.push({
          id: user.institutionId,
          name: user.institutionName
        })

        Object.keys(user).forEach(key => {
          if (_.has(this.userFormInfo, key)) {
            this.userFormInfo[key] = _.get(user, key, '')
            this.userFormInfo[key] = this.userFormInfo[key] ? this.userFormInfo[key] : ''
          }
          if (_.has(this.userFormQualify, key)) {
            this.userFormQualify[key] = _.get(user, key, '')
            this.userFormQualify[key] = this.userFormQualify[key] ? this.userFormQualify[key] : ''
          }
        })
        this.userFormInfo.isParticipationConsultation = user.isParticipationConsultation
        this.userFormInfo.isRecommend = user.isRecommend
        // 接口没有同名字段
        this.userFormInfo.areaSelected = [user.provinceId, user.cityId, user.countyId]

        // 接口没有同名字段
        user.roleVoList.forEach(role => {
          this.userFormInfo.roleSelected.push(role.roleId)
        })

        // 图片链接修正
        if (this.userFormInfo.headUrl) {
          this.userFormInfo.headUrl = this.imageServiceURL + this.userFormInfo.headUrl
        }
        if (this.userFormInfo.signUrl) {
          this.userFormInfo.signUrl = this.imageServiceURL + this.userFormInfo.signUrl
        }

        // 图片列表中的链接修正
        this.imageUrlMap.forEach(map => {
          const list = this.userFormQualify[map.stringKey].split('|')
          list.forEach(url => {
            if (url) {
              this[map.arrayKey].push({
                name: url,
                url: `${this.imageServiceURL}${url}`
              })
            }
          })
        })

        this.userDataReady = true
      } else {
        this.$message.warning('获取用户数据失败')
      }
    },
    headUrlSuccess(res) {
      this.userFormInfo.headUrl = res.url
    },
    signUrlSuccess(res) {
      this.userFormInfo.signUrl = res.url
    },
    submitForm() {
      let flag = false
      this.$refs.userFormInfo.validate(valid => {
        if (valid) {
          flag = true
          this.submitUser()
        } else {
          this.$message.warning('请填选正确的信息')
        }
      })
      return flag
    },
    async submitUser() {
      // 前端数据为null给后端,后端会做处理
      // 处理参数,处理的参数为必填项目
      const userTemp = _.assign({}, this.userFormInfo, this.userFormQualify)

      // 工龄修正
      userTemp.workYear = parseInt(userTemp.workYear, 10)
      // 角色数据修正
      userTemp.roles = []
      this.userFormInfo.roleSelected.forEach(roleId => {
        userTemp.roles.push({
          id: roleId
        })
      })
      // 地市区数据修正
      const areaKeyList = ['provinceId', 'cityId', 'countyId']
      this.userFormInfo.areaSelected.forEach((areaId, index) => {
        userTemp[areaKeyList[index]] = areaId
      })
      // 图片链接修正
      if (userTemp.headUrl) {
        userTemp.headUrl = userTemp.headUrl.slice(userTemp.headUrl.indexOf('_') - 1)
      }
      if (userTemp.signUrl) {
        userTemp.signUrl = userTemp.signUrl.slice(userTemp.signUrl.indexOf('_') - 1)
      }

      // 图片列表中的链接修正
      this.imageUrlMap.forEach(map => {
        userTemp[map.stringKey] = ''
        // 直接读取组件文件列表
        this.$refs[map.ref].uploadFiles.forEach(file => {
          // 判断为上传链接还是请求后载入的链接
          if (file.response) {
            const { url } = file.response
            const currentUrl = url.slice(url.indexOf('_') - 1)
            userTemp[map.stringKey] += `${currentUrl}|`
          } else {
            const { url } = file
            const currentUrl = url.slice(url.indexOf('_') - 1)
            userTemp[map.stringKey] += `${currentUrl}|`
          }
        })
      })

      if (this.isAddNew) {
        this.$axios({
          method: 'POST',
          url: '/users',
          data: userTemp
        }).then(
          res => {
            if (res && res.data.code === 200) {
              this.isAddSuccess = true
            } else {
              this.$message.warning(res.data.message)
            }
          },
          err => {
            this.$message.info(`${err.response.data.message}`)
          }
        )
      } else {
        this.$axios({
          method: 'PUT',
          url: '/users',
          data: userTemp
        }).then(
          res => {
            if (res && res.data.code === 200) {
              this.$message.success(
                '更新用户成功,登录名和手机号为登录账号,如果修改了登录名和手机号,请退出并重新登录'
              )
            } else {
              this.$message.warning(res.data.message)
            }
          },
          err => {
            this.$message.info(`${err.response.data.message}`)
          }
        )
      }
    },
    goBack() {
      this.$router.go(-1)
    }
  }
}
</script>

<style scoped>
.el-upload__tip_fix {
  margin-top: -15px;
}

.success-page div {
  text-align: center;
  margin-top: 60px;
}

.success-page .success-icon {
  font-size: 80px;
  color: #67c23a;
}

.success-page .success-h1 {
  font-size: 40px;
  color: #67c23a;
}

.success-page .success-h2 {
  font-size: 18px;
}

.row-class {
  margin-top: 20px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 146px;
  height: 146px;
  line-height: 146px;
  text-align: center;
}

.avatar {
  width: 146px;
  height: 146px;
  display: block;
}

.message-gutter {
  margin-bottom: 10px;
}
</style>
